<template>
  <div class="article-form" style="overflow-y: auto">
    <el-upload
      :before-upload="beforeAvatarUpload"
      :headers="csrfToken"
      :on-success="handleAvatarSuccess"
      :show-file-list="false"
      action="/api/upload/"
      class="avatar-uploader"
    >
      <div v-if="state.article.cover" class="avatar">
        <el-icon>
          <document />
        </el-icon>
      </div>
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <div v-for="filename in state.filesname" :key="filename.id">
      <a href="" @click="(e) => getFileContent(e, filename.file_name)">{{
        filename.file_name
      }}</a>
    </div>
    <button @click="exportExcel">导出</button>
    <div id="result" contenteditable></div>
  </div>
</template>
<script lang="ts">
//@ts-ignore
import { ElMessage, ElMessageBox } from 'element-plus';
import { defineComponent, reactive, onMounted } from 'vue';
import XLSX from 'xlsx';

import {
  getArticleDetail,
  getCatalogTree,
  getTagList,
  remoteSaveArticle,
  getFileNameList,
  addFileName,
  getFilenameContent,
} from '../api/service';
import { Article, Catalog, Tag, TagList } from '../types';
import { getCookie } from '../utils';

export default defineComponent({
  name: 'EditArticle',
  props: {
    articleId: {
      type: Number,
      require: true,
      default: undefined,
    },
    visible: {
      type: Boolean,
      require: true,
    },
  },
  watch: {
    '$props.visible': {
      handler(val: Boolean, oldVal: Boolean) {
        if (val !== oldVal) {
          this.state.visible = val;
        }
      },
    },
  },
  emits: ['close'],
  setup(props, context) {
    const state = reactive({
      article: {} as Article,
      loading: false,
      visible: true as Boolean,
      catalogTree: [] as Array<Catalog>,
      tags: [] as Array<Tag>,
      catalogs: [] as Array<number>,
      filesname: [],
    });

    const saveArticle = async () => {
      try {
        state.loading = true;
        if (state.catalogs.length) {
          state.article.catalog = state.catalogs[state.catalogs.length - 1];
        } else {
          state.article.catalog = 111;
        }
        if (props.articleId) {
          await remoteSaveArticle('put', state.article);
        } else {
          await remoteSaveArticle('post', state.article);
        }
        state.loading = false;
        context.emit('close', true);
      } catch (e) {
        state.loading = false;
      }
    };
    const csrfToken = { 'X-CSRFToken': getCookie('csrftoken') };
    onMounted(function () {
      getFileNameList().then((res) => {
        console.log('res.results :>> ', res.results);
        state.filesname = res.results;
      });
    });
    return {
      state,
      saveArticle,
      csrfToken,
    };
  },
  methods: {
    async handleSearch() {
      (this.$refs.articleTitle as HTMLElement).focus();
      if (this.$props.articleId) {
        this.state.article = await getArticleDetail(this.$props.articleId);
        this.state.article.tags = this.state.article.tags_info.map(
          (tag: Tag) => tag.id
        );
        this.state.catalogs = this.state.article.catalog_info.parents;
      } else {
        this.state.article = {} as Article;
      }
      this.state.catalogTree = await getCatalogTree();

      if (!this.state.tags.length) {
        const tags: TagList = await getTagList({});
        this.state.tags = tags.results;
      }
    },
    getFileContent(e, name) {
      console.log('name :>> ', name);
      e.preventDefault();
      const u = window.encodeURIComponent(name);
      getFilenameContent(u).then((res) => {
        var data = new Uint8Array(res);
        var WorkBook = XLSX.read(data, { type: 'buffer' });
        var sheetname = WorkBook.SheetNames[0];
        console.log('WorkBook :>> ', WorkBook);
        console.log('WorkBook :>> ', WorkBook.Sheets[sheetname]);
        console.log(
          'WorkBook :>> ',
          XLSX.utils.sheet_to_csv(WorkBook.Sheets[sheetname])
        );
        var csv = XLSX.utils.sheet_to_csv(WorkBook.Sheets[sheetname]);
        console.log('csv :>> ', csv);
        document.getElementById('result').innerHTML = this.csv2table(csv);
      });
    },
    csv2table(csv) {
      console.log('1 :>> ', 1);
      var html = '<table>';
      var rows = csv.split('\n');
      const sample = rows.slice(1);
      const arr = [];
      sample.forEach((row) => {
        let columns = row.split(',');
        const sample = columns.slice(1);
        const obj = {
          hospitalName: sample[0],
          patientIncreased: sample[1],
          caseIncreased: sample[2],
          medicineCase: sample[3],
          surgeryTreat: sample[4],
          scale: sample[5],
          electroExam: sample[6],
        };
        arr.push(obj);
      });
      console.log('1111111111111111 :>> ', 1111111111111111);
      console.log(
        'arr :>> ',
        new Blob(arr, { type: 'application/javascript' })
      );
      this.openDownloadDialog(
        new Blob([JSON.stringify(arr)], { type: 'text/plain;charset=utf-8' }),
        '导出.txt'
      );
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        return buf;
      }
      rows.pop(); // 最后一行没用的
      rows.forEach(function (row, idx) {
        let index = 1; //记住当前索引 给每项数据后添加一项  遍历记住每一项多加一
        let columns = row.split(',');
        columns.forEach((v, i) => {
          columns.splice(i + index, 0, ' ');
          index += 1;
        });
        columns.unshift(idx + 1); // 添加行索引
        if (idx == 0) {
          // 添加列索引
          html += '<tr>';
          for (var i = 0; i < columns.length; i++) {
            html +=
              '<th>' +
              (i == 0
                ? ''
                : i % 2 === 0
                ? '修正值'
                : String.fromCharCode(65 + i - 1)) +
              '</th>';
            // +
            // '<th>' +
            // '修正值' +
            // '</th>';
          }
          html += '</tr>';
        }
        html += '<tr>';
        columns.forEach(function (column) {
          html += '<td>' + column + '</td>';
        });
        html += '</tr>';
      });
      html += '</table>';
      return html;
    },
    handleClose(done: any) {
      ElMessageBox.confirm('确认关闭抽屉?', '提示', {
        confirmButtonText: '关闭',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then((_: any): void => {
          this.$emit('close', false);
          this.state.article = {} as Article;
          done();
        })
        .catch((_: any): void => {
          console.error(_);
        });
    },
    //导出csv文件
    tb2csv(tbId) {
      var $trs = document.querySelector('#' + tbId).querySelectorAll('tr'); //表格id元素
      var str = '';
      for (var i = 0; i < $trs.length; i++) {
        var $tds =
          i === 0
            ? $trs[i].querySelectorAll('th')
            : $trs[i].querySelectorAll('td');
        for (var j = 0; j < $tds.length; j++) {
          str += $tds[j].innerText + ',';
        }
        str += '\n';
      }
      var csv = str; //'data:text/csv;charset=utf-8,\ufeff' +
      console.log('str :>> ', str);
      return csv;
      // var link = document.createElement('a');
      // link.setAttribute('href', csv);
      // link.setAttribute('download', new Date().getTime() + '.csv'); //文件名
      // link.click(); //下载文件
    },
    // csv转sheet对象
    csv2sheet(csv) {
      var sheet = {}; // 将要生成的sheet
      csv = csv.split('\n');
      csv.forEach(function (row, i) {
        row = row.split(',');
        if (i == 0)
          sheet['!ref'] =
            'A1:' + String.fromCharCode(65 + row.length - 1) + (csv.length - 1);
        row.forEach(function (col, j) {
          sheet[String.fromCharCode(65 + j) + (i + 1)] = { v: col };
        });
      });
      return sheet;
    },
    openDownloadDialog(url, saveName) {
      if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); // 创建blob地址
      }
      var aLink = document.createElement('a');
      aLink.href = url;
      aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
      var event;
      if (window.MouseEvent) event = new MouseEvent('click');
      else {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent(
          'click',
          true,
          false,
          window,
          0,
          0,
          0,
          0,
          0,
          false,
          false,
          false,
          false,
          0,
          null
        );
      }
      aLink.dispatchEvent(event);
    },
    // 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
    sheet2blob(sheet, sheetName) {
      sheetName = sheetName || 'sheet1';
      var workbook = {
        SheetNames: [sheetName],
        Sheets: {},
      };
      workbook.Sheets[sheetName] = sheet;
      // 生成excel的配置项
      var wopts = {
        bookType: 'xlsx', // 要生成的文件类型
        bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
        type: 'binary',
      };
      var wbout = XLSX.write(workbook, wopts);
      var blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });
      // 字符串转ArrayBuffer
      function s2ab(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
        return buf;
      }
      return blob;
    },
    exportExcel(csv) {
      // const sheet=XLSX.utils.table_to_sheet(document.querySelectorAll('table')[0])
      var sheet = this.csv2sheet(this.tb2csv('result'));
      var blob = this.sheet2blob(sheet);
      this.openDownloadDialog(blob, '导出.xlsx');
    },
    handleAvatarSuccess(res: any, file: File) {
      console.log('res :>> ', res);
      this.state.article.cover = res.url;
      addFileName({ file_name: res.url }).then(async () => {
        const data = await getFileNameList();
        this.state.filesname = data.results;
      });
    },
    beforeAvatarUpload(file: File) {
      console.log('file :>> ', file);
      const isImage = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/jpg',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-excel',
      ].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        ElMessage.error('上传图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
      }
      return isImage && isLt2M;
    },
  },
});
</script>

<style lang="less">
.article-form {
  padding: 24px;
  overflow-y: auto;
  border-top: 1px solid #e8e8e8;
  height: calc(100% - 100px);
}

//抽屉//element-ui的drawer固定底部按钮
.el-drawer .el-drawer__body {
  margin-bottom: 50px;
  height: 100% !important;
}

.el-drawer__header {
  margin-bottom: 16px;
}
.demo-drawer__footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background-color: white;
}

//抽屉//去掉element-ui的drawer标题选中状态

:deep(:focus) {
  outline: 0;
}

.avatar-uploader {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  box-sizing: border-box;
  width: 125px;
  height: 100px;
  cursor: pointer;
  line-height: 100px;
  text-align: center;
  font-size: 20px;
}
table {
  display: table;
  border-collapse: separate;
  box-sizing: border-box;
  text-indent: initial;
  border-spacing: 2px;
  border-color: grey;
  border-collapse: collapse;
}
tbody {
  display: table-row-group;
  vertical-align: middle;
  border-color: inherit;
}
tr {
  display: table-row;
  vertical-align: inherit;
  border-color: inherit;
}
th {
  display: table-cell;
  vertical-align: inherit;
  font-weight: bold;
  text-align: -internal-center;
}
th,
td {
  border: solid 1px #6d6d6d;
  padding: 5px 10px;
}
</style>
